﻿#include "MyOpenGLWidget.h"

MyOpenGLWidget::MyOpenGLWidget(QWidget *parent)
	: QOpenGLWidget(parent)
	//, m_vbo(QOpenGLBuffer::VertexBuffer)
{
	points << QVector3D(0.0f, 0.1f, 0.0f) << QVector3D(0.0f, 0.1f, 0.1f) << QVector3D(0.0f, 0.1f, 0.2f) << QVector3D(0.0f, 0.1f, 0.3f) << QVector3D(0.0f, 0.1f, 0.4f)
		<< QVector3D(0.0f, 0.2f, 0.0f) << QVector3D(0.0f, 0.2f, 0.1f) << QVector3D(0.0f, 0.2f, 0.2f) << QVector3D(0.0f, 0.2f, 0.3f) << QVector3D(0.0f, 0.2f, 0.4f);
}

MyOpenGLWidget::~MyOpenGLWidget()
{}

void MyOpenGLWidget::initializeGL()
{
	initializeOpenGLFunctions();
	glClearColor(0.7, 0.7, 0.7, 1);
}

void MyOpenGLWidget::paintGL()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
 	AsGLCoordPainter coord;
 	coord.renderCoord();

	AsGLXYZPainter xyz;
	//xyz.setTransformParam(m_transformParam);
	xyz.render();
}

void MyOpenGLWidget::resizeGL(int w, int h)
{
	Q_UNUSED(w);; Q_UNUSED(h);
	//glViewport(0, 0, w, h);
	projectionMatrix.setToIdentity();
	projectionMatrix.perspective(20.0f, (float)w / (float)h, 0.1f, 100.0f);
}

void MyOpenGLWidget::drawCoordinateAxes()
{
	QVector<float> vertices = {
		// X-axis arrow
		0.0f, 0.0f, 0.0f, // Origin
		1.0f, 0.0f, 0.0f, // X-axis endpoint
		//0.8f, 0.05f, 0.0f, // Arrowhead
		//0.8f, -0.05f, 0.0f, // Arrowhead

		// Y-axis arrow
		0.0f, 0.0f, 0.0f, // Origin
		0.0f, 1.0f, 0.0f, // Y-axis endpoint
		//0.05f, 0.8f, 0.0f, // Arrowhead
		//-0.05f, 0.8f, 0.0f, // Arrowhead

		// Z-axis arrow
		0.0f, 0.0f, 0.0f, // Origin
		-0.3f, -0.3f, 1.0f, // Z-axis endpoint
		//0.05f, 0.0f, 0.8f, // Arrowhead
		//-0.05f, 0.0f, 0.8f  // Arrowhead
	};

	QVector<unsigned int> indices = {
		0, 1, // X-axis line
		1, 2, // X-axis arrowhead
		1, 3, // X-axis arrowhead

		4, 5, // Y-axis line
		5, 6, // Y-axis arrowhead
		5, 7, // Y-axis arrowhead

		8, 9, // Z-axis line
		9, 10, // Z-axis arrowhead
	};

	QVector<float> colors = {
		// Colors for the axes (R, G, B)
		1.0f, 0.0f, 0.0f, // Red for X-axis
		1.0f, 0.0f, 0.0f,
		0.0f, 1.0f, 0.0f, // Green for Y-axis
		0.0f, 1.0f, 0.0f,
		0.0f, 0.0f, 1.0f, // Blue for Z-axis
		0.0f, 0.0f, 1.0f
	};

	vao.create();
	vao.bind();

	vbo.create();
	vbo.bind();
	vbo.allocate(vertices.constData(), vertices.size() * sizeof(float));

	GLuint vertexLocation = 0; // Location of the vertex attribute in the shader
	shaderProgram->enableAttributeArray(vertexLocation);
	shaderProgram->setAttributeBuffer(vertexLocation, GL_FLOAT, 0, 3);

	GLuint colorLocation = 1; // Location of the color attribute in the shader
	shaderProgram->enableAttributeArray(colorLocation);
	shaderProgram->setAttributeArray(colorLocation, GL_FLOAT, colors.constData(), 3);
	shaderProgram->setAttributeBuffer(colorLocation, GL_FLOAT, 0, 3 * sizeof(float));

	glLineWidth(1.0f);
	glDrawArrays(GL_LINES, 0, 6);
	//glDrawElements(GL_LINES, indices.size(), GL_UNSIGNED_INT, nullptr);
	//ibo.release();

	vbo.release();
	vao.release();
}
